package com.zs.controller;

import com.zs.entity.User;
import com.zs.service.UserService;
import com.zs.util.PageCommon;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUsers")
    public String getUsers(Model model) {
        List<User> list = userService.getUsers();
        if (list.size() > 0) {
            model.addAttribute("list", list);
        }
        return "users";
    }


    /**
     * 分页查询
     *
     * @param pageIndex 当前页
     * @return
     */
    @RequestMapping("/pageUserPage")
    public ModelAndView getUsersByPage(int pageIndex) {
        ModelAndView mv = new ModelAndView();

        //根据总条数和每页条数，得到总页数
        int userCount = userService.getUserCount();
        int totalPages = PageCommon.getTotalPages(userCount, PageCommon.PAGE_SIZE);

        if (pageIndex == 0) {
            pageIndex = 1;
        }

        if (pageIndex > totalPages) {
            pageIndex = totalPages;
        }

        Map<String, Integer> cond = new HashMap<>();
        cond.put("start", PageCommon.PAGE_SIZE * (pageIndex - 1));
        cond.put("length", PageCommon.PAGE_SIZE);

        List<User> list = userService.getUsersByPage(cond);

        //分别将当前页，用户列表，总页数存在request域当中，便于页面取值
        mv.addObject("pageIndex", pageIndex);
        mv.addObject("list", list);
        mv.addObject("totalPages", totalPages);

        mv.setViewName("users");
        return mv;

    }


}
